package com.orion.config.global;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Administrator
 * @date 2021/10/28
 */
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    public static final Integer CUSTOM_GLOBAL_FILTER_ORDER = 0;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("<-------------- BEGIN in custom global filter -------------->");
        System.out.println("let us see what is ServerWebExchange : " + exchange);
        //直接下一个
        //return chain.filter(exchange);
        long startTime = System.currentTimeMillis();

        return chain.filter(exchange).then().then(Mono.fromRunnable(() -> {
            //调用请求之后统计时间
            long endTime = System.currentTimeMillis();
            System.out.println(exchange.getRequest().getURI().getRawPath() + ", cost time : " + (endTime - startTime) + "ms");
            System.out.println("<-------------- END in custom global filter -------------->");
        }));
    }

    @Override
    public int getOrder() {
        return CUSTOM_GLOBAL_FILTER_ORDER;
    }
}
